<?php
/**
 * 商品评论数据统计
 * Enter description here ...
 * @author nijn
 *
 */
class GoodsCommentStatistics extends CActiveRecordBehavior{

	public $companys = array('Hotel', 'Scenic');
	
	public function companyCriteria($type, $id, $limit = 0, $rate = null) {
		$owner = $this->owner;
		$criteria = new CDbCriteria();
		if ($type == 'Hotel') {
			$table = 'goods_hotel';
			$companyId = 'hotel_id';
		} else if($type == 'Scenic') {
			$table = 'goods_scenic';
			$companyId = 'scenic_id';
		}
		$criteria->join = "LEFT JOIN {$table} c ON (t.target_object_id = c.goods_id)";
		$criteria->compare('target_object_type', $type);
		$criteria->compare('rate', $rate);
		$criteria->compare($companyId, $id);
		$criteria->limit = $limit;
		$criteria->order = 'rate asc';
		return $criteria;
	}
	
	public function commentSearch($pageSize = 10) {
		$criteria = new CDbCriteria();
		$model = $this->getOwner();
		if (in_array($model->target_object_type, $this->companys)) {
			$criteria = $this->companyCriteria($model->target_object_type, $model->target_object_id);
		} else {
			$criteria->compare('target_object_type', $model->target_object_type);
			$criteria->compare('target_object_id', $model->target_object_id);
		}
		$criteria->compare('rate', $model->rate);
		return new CActiveDataProvider($model, array(
			'criteria'=>$criteria,
			'pagination' => array(
				'pageSize' => $pageSize,
			)
		));
	}
	
	/**
	 * 获取评论数据
	 * Enter description here ...
	 * @param unknown_type $type
	 * @param unknown_type $id
	 */
	public function commentData($type, $id, $limit = 0) {
		$owner = $this->owner;
		$criteria = new CDbCriteria();
		$criteria->limit = $limit;
		$criteria->order = 'rate asc';
		if (in_array($type, $this->companys)) {
			$criteria = $this->companyCriteria($type, $id, $limit);
			return $owner->findAll($criteria);
		}
		return $owner->findAllByAttributes(array(
			'target_object_type' => $type,
			'target_object_id' => $id
		), $criteria);
	}
	
	
	/**
	 * 根据评分获取统计数
	 * Enter description here ...
	 * @param unknown_type $type
	 * @param unknown_type $id
	 * @param unknown_type $rate
	 */
	public function countByRate($type, $id, $rate) {
		$owner = $this->owner;
		if (in_array($type, $this->companys)) {
			$criteria = $this->companyCriteria($type, $id, 0, $rate);
			return $owner->count($criteria);
		}
		return $owner->countByAttributes(array(
			'target_object_type' => $type,
			'target_object_id' => $id,
			'rate' => $rate,
		));
	}
	
}

?>